<template>
  <div class="index">
     <!-- 原有控件 -->
    <div class="button-box">
      <el-button type="success" @click="openDialog">修改课程信息</el-button>
      <el-button type="success">删除课程</el-button>
    </div>

    <div class="course-info-card">
      <!-- 第一层 -->
      <div class="row row-top">
        <div class="left">
          <img class="course-img" src="../../assets/img/icon.png" alt="Course_Icon" />
          <span class="course-name">{{ course.courseName }}</span>
        </div>
        <div class="right">
          <span class="course-id">ID: {{ course.id }}</span>
        </div>
      </div>

      <el-divider />
      <!-- 第二层 -->
      <div class="row row-middle">
        <div class="left">
          <img class="teacher-avatar" src="../../assets/img/icon.png" alt="Teacher_Avatar" />
          <span class="teacher-name">{{ course.teacherName }}</span>
          <span class="teacher-id">(id:{{ course.teacherID }})</span>
        </div>
      </div>

      <!-- 第三层 -->
      <div class="row row-times">
        <div class="times">
          <div class="time-item">创建时间：{{ course.createTime }}</div>
          <div class="time-item">上次更新：{{ course.updateTime }}</div>
        </div>
      </div>

      <el-divider />
      <!-- 第四层 -->
      <div class="row row-desc">
        <p class="description">课程内容描述：{{ course.description }}</p>
      </div>
    </div>

    <div class="tree-header-divider">
      <el-divider>章节展示</el-divider>
    </div>

    <!-- 编辑章节按钮 -->
    <div class="tree-header-button">
      <el-button v-if="!editMode" type="primary" @click="toggleEdit">编辑章节</el-button>
      <el-button v-else type="success" @click="toggleEdit">编辑完成</el-button>
    </div>

    <!-- 章节区：编辑模式为表格，否则为树状 -->
    <div class="chapter-area">
      <template v-if="!editMode">
        <!-- 原树状列表 -->
        <div class="chapter-tree">
          <el-tree
            :data="treeData"
            node-key="id"
            :props="treeProps"
            @node-click="chapterClick"
            highlight-current
            >
            <template #default="{data}">
              <div class="chapter-node">
                <div class="item"><strong>chapter:</strong> {{ data.title }}</div>
                <div class="item"><strong>简略信息:</strong> {{ data.description }}</div>
                <div class="item"><strong>date:</strong> {{ data.createTime }}</div>
              </div>
            </template>
          </el-tree>
        </div>
      </template>

      <template v-else>
        <!-- 编辑模式：表格展示 -->
        <el-table :data="flatData" style="width: 100%">
          <el-table-column prop="level" label="层级" width="100" />
          <el-table-column label="标题">
            <template #default="{ row }">
              <div :style="{ paddingLeft: (row.level - 1) * 30 + 'px' }">
                <el-input v-model="row.title" size="small" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="描述">
            <template #default="{ row }">
              <el-input v-model="row.description" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="danger" icon="el-icon-delete" circle size="small" @click="removeChapter(row.id)" />
            </template>
          </el-table-column>
        </el-table>

        <div class="add-row" style="margin-top:0px; display:flex; gap:8px; align-items:center;">
          <el-text>选择父章节</el-text>
          <el-select v-model="newChapterParentID" placeholder="选择父章节" style="width:200px">
            <!-- 顶层选项 -->
            <el-option :key="0" label="顶层" :value="0" />
            <!-- 全路径选项 -->
            <el-option
              v-for="opt in parentOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
              />
          </el-select>
          <el-input v-model="newChapterTitle" placeholder="章节标题" style="width:200px" size="small" />
          <el-input v-model="newChapterDescription" placeholder="章节描述" style="width:200px" size="small" />
          <el-button type="primary" size="small" @click="confirmAdd(newChapterParentID)">添加章节</el-button>
        </div>

      </template>
    </div>

    <!-- 修改课程信息对话框 同上 -->
    <el-dialog title="修改课程信息" v-model="dialogVisible" width="500px">
      <el-form label-width="100px">
        <el-form-item label="课程名称">
          <el-input v-model="tempName" placeholder="修改课程名称" />
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input
            type="textarea"
            :rows="8"
            v-model="tempDescription"
            placeholder="修改课程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChange">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'
import router from '@/router';
import { format } from 'date-fns';
import { useCookies } from 'vue3-cookies'
const { cookies } = useCookies()

// 编辑模式
const editMode = ref(false)
function toggleEdit() {
  editMode.value = !editMode.value
}

// 课程基础
const course = reactive({ id: null, courseName: '', description: '', teacherID: null, teacherName: '', createTime:'', updateTime:'' })

// 弹窗相关
const dialogVisible = ref(false)
const tempName = ref('')
const tempDescription = ref('')

function openDialog() {
  dialogVisible.value = true
  tempName.value = course.courseName
  tempDescription.value = course.description
}

// 提交修改课程
function submitChange() {
  axios.post('/api/course/update', {
    id: course.id,
    courseName: tempName.value,
    description: tempDescription.value,
    teacherID: course.teacherID
  }).then(res => {
    console.log(res.data)
    course.courseName = tempName.value
    course.description = tempDescription.value
    cookies.remove('selectedCourse')
    cookies.set('selectedCourse', JSON.stringify(course))
    dialogVisible.value = false
  }).catch(err => console.error(err))
}

// 树状
const treeData = ref([])
const treeProps = { children: 'children', label: 'title' }

// 将树状数据平铺成列表，带层级信息
const flatData = computed(() => {
  const list = []
  function dfs(nodes, level) {
    nodes.forEach(n => {
      list.push({ id: n.id, title: n.title, description: n.description, level, createTime: n.createTime })
      if (n.children) dfs(n.children, level + 1)
    })
  }
  dfs(treeData.value, 1)
  return list
})

// 这里是新增：根据 treeData 递归生成“顶级--子级--…--本级”标签列表，渲染在添加章节部分
const parentOptions = computed(() => {
  const opts = []
  function dfs(nodes, path) {
    nodes.forEach(node => {
      const newPath = path.concat(node.title)
      opts.push({
        value: node.id,
        label: newPath.join('--')
      })
      if (node.children && node.children.length) {
        dfs(node.children, newPath)
      }
    })
  }
  dfs(treeData.value, [])
  return opts
})

// 添加、删除、查找、排序 同前
const newChapterParentID = ref(0)
const newChapterTitle = ref('')
const newChapterDescription = ref('')

// 递归工具
function findNode(list, id) {
  for (const node of list) {
    if (node.id === id) return node
    if (node.children) {
      const found = findNode(node.children, id)
      if (found) return found
    }
  }
  return null
}
function removeNode(list, id) {
  const idx = list.findIndex(n => n.id === id)
  if (idx !== -1) { list.splice(idx, 1); return true }
  for (const node of list) {
    if (node.children && removeNode(node.children, id)) return true
  }
  return false
}


function sortChapters(list) {
  return list.sort((a, b) => a.sortOrder - b.sortOrder)
             .map(i => ({ ...i, children: sortChapters(i.children || []) }))
}

// 获取章节
async function fetchChapters() {
  try {
    const res = await axios.get('/api/chapter/courseid', { params: { courseID: course.id } })
    if (res.data.code === 200) treeData.value = sortChapters(res.data.data)
  } catch (e) {
    console.error(e)
  }
}

// 添加章节
async function confirmAdd(parentID) {
  if (newChapterTitle.value.length <= 0) return
  const payload = { courseID: course.id, title: newChapterTitle.value, description: newChapterDescription.value }
  if (parentID !== 0) payload.parentID = parentID
  try {
    await axios.post('/api/chapter/add', payload)
    const formattedDate = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
    const payload2 = { courseID: course.id, title: newChapterTitle.value, description: newChapterDescription.value, create_time: formattedDate, parentID: parentID}
    if (parentID === 0) {
      treeData.value.push({ ...payload2, children: [] })
    } else {
      const parent = findNode(treeData.value, parentID)
      parent.children = parent.children || []
      parent.children.push({ ...payload2, children: [] })
    }
    // 重置输入
    newChapterParentID.value = 0
    newChapterTitle.value = ''
    newChapterDescription.value = ''
    treeData.value = sortChapters(treeData.value)
  } catch (err) {
    console.error('添加失败', err)
  }
}

// 删除章节
async function removeChapter(id) {
  try {
    await axios.delete(`/api/chapter/delete?id=${id}`)
    removeNode(treeData.value, id)
  } catch (err) {
    console.error('删除失败', err)
  }
}

function chapterClick(data) { 
  cookies.remove('chapterId')
  if(data.parentID){
    cookies.set('chapterId', data.id)
    router.push({ path : '/teacher/courseManage/courseInfoDetail'})
  }
}

onMounted(()=>{
  const stored = cookies.get('selectedCourse')
  if (stored) Object.assign(course, stored)
  fetchChapters()
})
</script>

<style scoped lang="less">
.add-row {
  width: 90%;
  margin-left: 5%;
}
.index { 
  padding-bottom: 20px; 
}
.course-info-card { 
  border:1px solid #ebeef5; 
  border-radius:6px; 
  padding: 16px;
  margin:0 8%; 
  background:#fff; 
  font-family:"Helvetica Neue",Arial,sans-serif; 
}
.row { 
  display:flex; 
  align-items:center; 
  justify-content:space-between; 
  margin-bottom:12px; 
}
.row-top .left { 
  display:flex; 
  align-items:center; 
}
.course-img { 
  width:60px; 
  height:60px; 
  object-fit:cover; 
  border-radius:4px; 
  margin-right:12px; 
}
.course-name {
  font-size:24px;
  font-weight:bold; 
  color:#000; 
}
.row-top .right .course-id { 
  font-size:12px; 
  color:#909399; 
}
.row-middle .left { 
  display:flex; 
  align-items:center; 
}
.teacher-avatar { 
  width:40px; 
  height:40px; 
  object-fit:cover; 
  border-radius:50%; 
  margin-right:8px; 
}
.teacher-name { 
  font-size:16px; 
  color:#333; 
  margin-right:4px; 
}
.teacher-id { 
  font-size:14px; 
  color:#909399; 
}
.row-times .times { 
  display:flex; 
  flex-direction:column; 
}
.time-item { 
  font-size:12px; 
  color:#909399; 
  line-height:1.4; 
}
.row-desc .description { 
  font-size:14px; 
  color:#606266; 
  line-height:1.6; 
  margin:0; 
}
.button-box { 
  margin:10px 0; 
}
.tree-header-button { 
  width:15%; 
  margin-left:80%; 
  margin-bottom:20px; 
  margin-top: 20px;
}
.chapter-tree { 
  width:84%; 
  margin:0 8%; 
  overflow-y:auto; 
  background-color:#9adcff; 
  border:1px solid #888; 
  border-radius:10px; 
}
.chapter-list, .child-list { 
  list-style:none; 
  padding-left:16px; 
}

.chapter-content { 
  display:flex; 
  align-items:center; 
  gap:8px; 
}
.inline-input { 
  width:200px; 
}
.add-item { 
  margin-left:16px; 
}

.tree-header-divider {
  margin-top: 20px;
}

.chapter-tree {
  /* 确保树容器有明确高度和溢出控制 */
  height: 100%; /* 或指定固定高度如500px */
  width: 84%;
  margin-left: 8%;
  overflow-y: auto; /* 章节树整体可滚动 */
  color: #fff;            /* 白色文字确保对比度 */
  border: 1px solid #888; 
  border-radius: 10px;     /* 可选：圆角修饰 */
  background-color: #9adcff;  /* 纯黑背景 */
}

.chapter-tree ::v-deep .el-tree-node > .el-tree-node__content {
  height: 60px !important;  /* 固定节点高度 */
  min-height: 60px;         /* 确保最小高度 */
  padding: 12px 8px;        /* 增加内边距 */
  box-sizing: border-box;   /* 防止padding影响高度计算 */
  white-space: normal;      /* 允许文本换行 */
  align-items: flex-start;  /* 顶部对齐内容 */
}

.chapter-tree ::v-deep .el-tree-node__content:hover {
  background-color: #d8f1ff !important; /* 深灰悬浮色 */
}
.chapter-tree ::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #cae7ff !important; /* 当前节点更亮灰色 */
}

.chapter-node {
  display: flex;
  gap: 20px; /* 增大间距避免重叠 */
  min-height: 0px; /* 固定最小高度，根据内容扩展 */
  box-sizing: border-box; /* 防止padding影响高度计算 */
}

.item {
  font-size: 14px;
  white-space: normal; /* 允许换行 */
  word-break: break-word; /* 长单词或URL强制换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 文本溢出显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制最多2行 */
  -webkit-box-orient: vertical;
}
</style>
